import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

public final class PlayerClient extends Client {

	private static BufferedReader line;
	private static Thread inputThread;

	PlayerClient() {
		super();
		line = new BufferedReader(new InputStreamReader(System.in));
	}

	@Override
	public void listen(){
		String response = "";
			while (((response = this.getLine()) != null) && (isOn())) {
				if (response.indexOf("***Bye") != -1) {
					System.out.println(response);
					System.exit(0);
				}
				else if(!response.startsWith("~")){
					System.out.println(response);
				}

			}

	}

	
	private void createShutdownHook() {
		try {
			Runtime.getRuntime().addShutdownHook(new Thread() {
				public void run() {

					inputThread.interrupt();
					this.interrupt();
					quit();
					try {
						inputThread.join();
					} catch (InterruptedException e) {

					}
					close();
				}
			});
			
			System.out.println("[Main thread] Shutdown hook added");
		} catch (Throwable t) {
			// we get here when the program is run with java
			// version 1.2.2 or older
			System.out.println("[Main thread] Could not add Shutdown hook");
		}
	}
	
	private void write(){
		try {
			while (isOn()) {
				sendLine(line.readLine().trim());
			}
		} catch (IOException e) {
			System.out.println("Error reading this line");
			System.exit(0);
		}
		catch (NullPointerException ex){
			
		}
	}
	
	public void setup() {

		this.connect();
		createShutdownHook();
		System.out.println("Creating new listening thread");
		inputThread = new PlayerClient();
		inputThread.start();



		write();

	}
	
	public static void main(String args[]){
		PlayerClient client = new PlayerClient();
		client.getData();
		client.setup();
	}
}
